<script setup lang="ts">
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import {  ref,computed,watch } from 'vue';
const List = ref(JSON.parse(localStorage.getItem('to-do-Vue3') || '[]') as  {
    id: number;
    name: string;
    done: boolean;
  }[]) 


/** 添加事件 */
const handleAddItem = (name:string) => {
  List.value = [{
    id:Date.now(),
    done:false,
    name,
  },...List.value]
}

/** 计算选中值 */
const todo_count = computed(()=>{
return List.value.filter(item=>!item.done).length
})

/** 改变底部的状态栏 */
const type = ref('All')
const changeType = (typeData:string) => {
  type.value = typeData
}


/** 根据类型计算呈现的list */
const todo_list =  computed(()=>{
return List.value.filter(item=>{
if(type.value == 'Active') return !item.done
if(type.value == 'Completed') return item.done
return item
})
})


/** 删除所有已完成事件 */
const handleClear = () => {
  List.value = List.value.filter(item=>!item.done)
}

/** 全选影响小选 */
const checkall = (check:boolean) => {
  List.value.forEach(item=>item.done = check)
}


/** 删除单个事件 */
const handleDelItem = (index: number) => {
  List.value.splice(index, 1)
}

/** 改变单个选中按钮事件 */
const handleChecked = (id: number) => {
  const index = List.value.findIndex(item => item.id == id)
  List.value[index].done = !List.value[index].done
}

/** 深度监听 持久化储存 */
watch(List,() => {
  localStorage.setItem('to-do-Vue3',JSON.stringify(List.value))
},{deep:true,immediate:true})
</script>

<template>
  <section class="todoapp">
    <TodoHeader :handleAddItem="handleAddItem" />
    <TodoMain :list="todo_list" @checkall="checkall" @handleChecked="handleChecked" @handleDelItem="handleDelItem" />
    <TodoFooter  :todo_count="todo_count" :type="type" @changeType="changeType" :handleClear="handleClear" />
  </section>
</template>

<style></style>
